<?php
require_once('thumb.php');

function _404($message)
{
    @header("HTTP/1.0 404 Not Found");
    @header("Content-type: text/html; charset=utf-8");
    exit($message);
}

$uri = $_SERVER['REQUEST_URI'];

preg_match('#/thumb/([\w\=\-/\+\%`~\.]+)\.((\d+)|(c\d+x\d+))\.(jpe?g|png|w?bmp|gif)$#', $uri, $matches);

if (count($matches) != 6)
{
    _404('无效的缩略图文件格式');
}

list($filename, $basename, $size, , , $ext) = $matches;

$source = dirname(__FILE__)."/$basename.$ext";

if ( ! is_file($source))
{
    _404("图片源文件不存在：$source");
}

try
{
    $thumb = new Thumb($source);
    if ($size[0] == 'c')
    {
        // 获取图片原始信息
        $orig_size = getimagesize($source);

        // 获取缩略图尺寸
        list($width, $height) = explode('x', ltrim($size, 'c'));

        // 计算缩略图与原始图宽高比
        $proportion = round(min($orig_size[0] / $width, $orig_size[1] / $height), 4);

        // 以中心为原点裁剪
        $thumb->crop_center($width * $proportion, $height * $proportion);

        // 生成比例裁剪文件
        $prop_file = dirname(__FILE__)."/thumb/$basename.p$proportion.$ext";
        if ( ! is_file($prop_file))
        {
            $thumb->build($prop_file);
        }

        // 设定图片源文件为比例裁剪文件
        $thumb->set_source($prop_file);
        $thumb->make($width, $height);
    }
    else
    {
        $thumb->make($size, $size);
    }
    $thumb->output(TRUE, dirname(dirname(__FILE__)).$uri);
}
catch (Exception $e)
{
    exit($e->getMessage());
}